import Facebook from "./Facebook";
import Logger from "../Logger/Logger";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class FacebookRewardedVideoAd {

    //属性声明
    // @property(cc.Label)     // 使用 property 装饰器声明属性，括号里是属性类型，装饰器里的类型声明主要用于编辑器展示
    // label: cc.Label = null; // 这里是 TypeScript 用来声明变量类型的写法，冒号后面是属性类型，等号后面是默认值

    // 也可以使用完整属性定义格式
    // @property({
    //     visible: false
    //     displayName: "Score (player)"
    //     tooltip: "The score of player"
    // })
    // text: string = 'hello';

    private mLogTag: string = null;
    private mAdUnitId: string = null;
    private mRewardedVideoAd: FBInstant.AdInstance = null;
    private mRewardedVideoAdLoading = false;
    private mRewardedVideoAdLoaded = false;

    public constructor(adUnitId: string, logTag: string = null) {
        this.mAdUnitId = adUnitId;
        this.mLogTag = logTag;
        this.init();
    }


    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    // onEnable() {}
    // start() {}
    // update(dt) {}
    // lateUpdate(dt) {}
    // onDisable() {}
    // onDestroy() {}

    private init() {
        if (!Facebook.IsFBInit()) {
            return;
        }
        this.loadRewardedVideoAd();
    }

    private loadRewardedVideoAd(successCallback: Function = null, failCallback: Function = null) {
        if (!Facebook.IsApiSupport("getRewardedVideoAsync")) {
            return;
        }
        if (this.mRewardedVideoAdLoading) {
            this.logDebug("mRewardedVideoAdLoading");
            return;
        }
        if (this.mRewardedVideoAdLoaded) {
            if (successCallback) {
                successCallback();
            }
            return;
        }
        this.mRewardedVideoAdLoading = true;
        this.mRewardedVideoAdLoaded = false;
        if (this.mRewardedVideoAd == null) {
            FBInstant.getRewardedVideoAsync(this.mAdUnitId).then((rewardedVideo) => {
                this.mRewardedVideoAd = rewardedVideo;
                this.loadRewardedVideoAdInternal(successCallback, failCallback);
            }).catch((err) => {
                this.mRewardedVideoAdLoading = false;
                this.mRewardedVideoAdLoaded = false;
                this.logError('loadRewardedVideoAd Fail : ' + err.code + " :: " + err.message);
                if (failCallback) {
                    failCallback();
                }
            });
        } else {
            this.loadRewardedVideoAdInternal(successCallback, failCallback);
        }
    }

    private loadRewardedVideoAdInternal(successCallback: Function = null, failCallback: Function = null) {
        if (this.mRewardedVideoAd == null) return;
        this.mRewardedVideoAd.loadAsync().then(() => {
            this.mRewardedVideoAdLoading = false;
            this.mRewardedVideoAdLoaded = true;
            this.logDebug("loadRewardedVideoAdInternal done");
            if (successCallback) {
                successCallback();
            }
        }).catch((err) => {
            this.mRewardedVideoAdLoading = false;
            this.mRewardedVideoAdLoaded = false;
            this.logError('loadRewardedVideoAdInternal Fail : ' + err.code + " :: " + err.message);
            if (failCallback) {
                failCallback();
            }
        });
    }

    public showRewardedVideoAd(successCallback: Function = null, failCallback: Function = null) {
        if (!Facebook.IsFBInit()) {
            if (failCallback) {
                failCallback();
            }
            return;
        }

        if (this.mRewardedVideoAd == null || !this.mRewardedVideoAdLoaded) {
            this.loadRewardedVideoAd(() => {
                this.showRewardedVideoAdInternal(successCallback, failCallback);
            }, failCallback);
            return;
        }
        this.showRewardedVideoAdInternal(successCallback, failCallback);
    }

    private showRewardedVideoAdInternal(successCallback: Function = null, failCallback: Function = null) {
        if (!Facebook.IsFBInit() || this.mRewardedVideoAd == null || !this.mRewardedVideoAdLoaded) {
            if (failCallback) {
                failCallback();
            }
            return;
        }

        this.logDebug("showRewardedVideoAdInternal");
        let rewardedVideoAd = this.mRewardedVideoAd;
        rewardedVideoAd.showAsync().then(() => {
            if (successCallback) {
                successCallback();
            }
            this.mRewardedVideoAd = null;
            this.loadRewardedVideoAd();
        }).catch((err) => {
            if (failCallback) {
                failCallback();
            }
            this.mRewardedVideoAd = null;
            this.logError('showRewardedVideoAdInternal Fail : ' + err.code + " :: " + err.message);
        });
        this.mRewardedVideoAd = null;
        this.mRewardedVideoAdLoaded = false;
    }

    private logDebug(log?: any, ...optionalParams: any[]) {
        if (this.mLogTag) {
            log = this.mLogTag + "_" + log;
        }
        Logger.log(log, optionalParams);
    }

    private logError(log?: any, ...optionalParams: any[]) {
        if (this.mLogTag) {
            log = this.mLogTag + "_" + log;
        }
        Logger.error(log, optionalParams);
    }
}
